<?php

namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\Request;
use think\response\Json;

class Adbanner extends BaseController
{
    /**
     * 广告横幅列表
     *
     * @param Request $request
     * @return Json
     */
    public function list(Request $request): Json
    {
        try {
            $param = $request->param();

            $page = $param['page'] ?? 1;
            $limit = $param['limit'] ?? 10;

            $map = [];

            // 搜索条件
            if ($param['id'] ?? "") {
                $map[] = ['id', '=', $param['id']];
            }

            if ($param['title'] ?? "") {
                $map[] = ['title', 'like', '%' . $param['title'] . '%'];
            }

            if ($param['media_type'] ?? "") {
                $map[] = ['media_type', '=', $param['media_type']];
            }

            if ($param['status'] ?? "") {
                $map[] = ['status', '=', $param['status']];
            }

            if (isset($param['position']) && $param['position'] !== "") {
                $map[] = ['position', '=', $param['position']];
            }

            // 查询数据
            $dataObj = Db::name('ad_banner')
                ->where($map)
                ->order('position', 'asc')
                ->order('updated_at', 'desc')
                ->fetchSql(false)
                ->page($page, $limit)
                ->select();

            $dataArr = $dataObj->toArray();

            // 处理数据
            foreach ($dataArr as $key => $value) {
                $dataArr[$key]['id'] = strval($value['id']);

                // 处理媒体类型描述
                if ($value['media_type'] == 'IMAGE') {
                    $dataArr[$key]['media_type_desc'] = '图片';
                } elseif ($value['media_type'] == 'VIDEO') {
                    $dataArr[$key]['media_type_desc'] = '视频';
                } else {
                    $dataArr[$key]['media_type_desc'] = '未知类型';
                }

                // 处理状态描述
                if ($value['status'] == 'NORMAL') {
                    $dataArr[$key]['status_desc'] = '正常';
                } elseif ($value['status'] == 'DISABLE') {
                    $dataArr[$key]['status_desc'] = '禁用';
                } else {
                    $dataArr[$key]['status_desc'] = '未知状态';
                }

                // 处理是否可跳转
                if ($value['is_linkable'] == 0) {
                    $dataArr[$key]['is_linkable_desc'] = '不可跳转';
                } elseif ($value['is_linkable'] == 1) {
                    $dataArr[$key]['is_linkable_desc'] = '可跳转';
                } else {
                    $dataArr[$key]['is_linkable_desc'] = '未知';
                }

                // 处理链接类型
                if ($value['link_type'] == 'IN_SITE') {
                    $dataArr[$key]['link_type_desc'] = '站内链接';
                } elseif ($value['link_type'] == 'OUT_SITE') {
                    $dataArr[$key]['link_type_desc'] = '站外链接';
                } else {
                    $dataArr[$key]['link_type_desc'] = '';
                }

                // 处理缩略图
                if (!empty($value['thumb_image'])) {
                    $dataArr[$key]['thumb_image'] = config('basic.cdn') . $value['thumb_image'];
                } else {
                    $dataArr[$key]['thumb_image'] = '';
                }

                // 处理媒体链接
                if (!empty($value['media_url'])) {
                    $dataArr[$key]['media_url'] = config('basic.cdn') . $value['media_url'];
                } else {
                    $dataArr[$key]['media_url'] = '';
                }
            }

            // 查询总数
            $count = Db::name('ad_banner')->where($map)->count();

            return json(['code' => 0, 'msg' => 'success', 'data' => ['list' => $dataArr, 'count' => $count]]);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => '获取广告横幅列表失败：' . $e->getMessage()]);
        }
    }

    /**
     * 创建广告横幅
     *
     * @param Request $request
     * @return Json
     */
    public function create(Request $request): Json
    {
        try {
            $param = $request->param();

            // 验证必要参数
            if (empty($param['title'])) {
                return json(['code' => -1, 'msg' => '广告标题不能为空']);
            }

            if (empty($param['thumb_image'])) {
                return json(['code' => -1, 'msg' => '缩略图不能为空']);
            }

            if (empty($param['media_type'])) {
                return json(['code' => -1, 'msg' => '媒体类型不能为空']);
            }

            if (empty($param['media_url'])) {
                return json(['code' => -1, 'msg' => '媒体资源链接不能为空']);
            }

            if (!isset($param['is_linkable'])) {
                return json(['code' => -1, 'msg' => '是否可跳转不能为空']);
            }

            // 如果可跳转，则链接类型和链接内容不能为空
            if (intval($param['is_linkable']) === 1) {
                if (empty($param['link_type'])) {
                    return json(['code' => -1, 'msg' => '链接类型不能为空']);
                }
                if (empty($param['link_text'])) {
                    return json(['code' => -1, 'msg' => '链接内容不能为空']);
                }
            }

            // 准备数据
            $data = [
                'title' => $param['title'],
                'thumb_image' => $param['thumb_image'],
                'media_type' => $param['media_type'],
                'media_url' => $param['media_url'],
                'is_linkable' => intval($param['is_linkable']),
                'link_type' => $param['link_type'] ?? null,
                'link_text' => $param['link_text'] ?? null,
                'position' => $param['position'] ?? 0,
                'status' => $param['status'] ?? 'NORMAL',
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ];

            // 插入数据
            $id = Db::name('ad_banner')->insertGetId($data);

            if (!$id) {
                return json(['code' => -1, 'msg' => '创建广告横幅失败']);
            }

            return json(['code' => 0, 'msg' => '创建成功', 'data' => ['id' => strval($id)]]);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => '创建广告横幅失败：' . $e->getMessage()]);
        }
    }

    /**
     * 更新广告横幅
     *
     * @param Request $request
     * @param int $id
     * @return Json
     */
    public function update(Request $request, $id): Json
    {
        try {
            $param = $request->param();

            // 检查广告横幅是否存在
            $adBanner = Db::name('ad_banner')->where('id', $id)->find();
            if (!$adBanner) {
                return json(['code' => -1, 'msg' => '广告横幅不存在']);
            }

            // 准备更新数据
            $data = [];

            if (isset($param['title'])) {
                $data['title'] = $param['title'];
            }

            if (isset($param['thumb_image'])) {
                $data['thumb_image'] = $param['thumb_image'];
            }

            if (isset($param['media_type'])) {
                $data['media_type'] = $param['media_type'];
            }

            if (isset($param['media_url'])) {
                $data['media_url'] = $param['media_url'];
            }

            if (isset($param['is_linkable'])) {
                $data['is_linkable'] = intval($param['is_linkable']);
                
                // 如果设置为不可跳转，清空链接相关字段
                if (intval($param['is_linkable']) === 0) {
                    $data['link_type'] = null;
                    $data['link_text'] = null;
                }
            }

            if (isset($param['link_type'])) {
                $data['link_type'] = $param['link_type'];
            }

            if (isset($param['link_text'])) {
                $data['link_text'] = $param['link_text'];
            }

            if (isset($param['position'])) {
                $data['position'] = intval($param['position']);
            }

            if (isset($param['status'])) {
                $data['status'] = $param['status'];
            }

            $data['updated_at'] = date('Y-m-d H:i:s');

            // 更新数据
            $result = Db::name('ad_banner')->where('id', $id)->update($data);

            if ($result === false) {
                return json(['code' => -1, 'msg' => '更新广告横幅失败']);
            }

            return json(['code' => 0, 'msg' => '更新成功']);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => '更新广告横幅失败：' . $e->getMessage()]);
        }
    }

    /**
     * 删除广告横幅
     *
     * @param Request $request
     * @param int $id
     * @return Json
     */
    public function delete(Request $request, $id): Json
    {
        try {
            // 检查广告横幅是否存在
            $adBanner = Db::name('ad_banner')->where('id', $id)->find();
            if (!$adBanner) {
                return json(['code' => -1, 'msg' => '广告横幅不存在']);
            }

            // 删除广告横幅
            $result = Db::name('ad_banner')->where('id', $id)->delete();

            if (!$result) {
                return json(['code' => -1, 'msg' => '删除广告横幅失败']);
            }

            return json(['code' => 0, 'msg' => '删除成功']);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => '删除广告横幅失败：' . $e->getMessage()]);
        }
    }

    /**
     * 更新广告状态
     *
     * @param Request $request
     * @return Json
     */
    public function updateStatus(Request $request): Json
    {
        try {
            $param = $request->param();

            if (empty($param['id'])) {
                return json(['code' => -1, 'msg' => '广告横幅ID不能为空']);
            }

            if (empty($param['status'])) {
                return json(['code' => -1, 'msg' => '状态不能为空']);
            }

            // 检查广告横幅是否存在
            $adBanner = Db::name('ad_banner')->where('id', $param['id'])->find();
            if (!$adBanner) {
                return json(['code' => -1, 'msg' => '广告横幅不存在']);
            }

            // 更新状态
            $result = Db::name('ad_banner')->where('id', $param['id'])->update([
                'status' => $param['status'],
                'updated_at' => date('Y-m-d H:i:s')
            ]);

            if ($result === false) {
                return json(['code' => -1, 'msg' => '更新状态失败']);
            }

            return json(['code' => 0, 'msg' => '更新状态成功']);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => '更新状态失败：' . $e->getMessage()]);
        }
    }
}